package xyz.labmem.main.application.controller.api.sys.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.labmem.main.annotation.RoleValid;
import xyz.labmem.main.application.controller.api.sys.user.request.UpdatePasswordRequest;
import xyz.labmem.main.application.controller.api.sys.user.request.UserListRequest;
import xyz.labmem.main.application.entity.sys.User;
import xyz.labmem.main.application.mapper.sys.UserMapper;
import xyz.labmem.main.application.service.sys.impl.FileServiceImpl;
import xyz.labmem.main.enums.StateEnum;
import xyz.labmem.main.result.ResultUtil;
import xyz.labmem.main.result.ResultVo;
import xyz.labmem.main.sys.StaticVariable;

import javax.validation.Valid;

/**
 * Created by Lty
 * Created in 11:00 2020-3-6
 */
@RestController
@Api(tags = "用户权限API")
@RequestMapping("/admin/user/api")
public class UserApi {

    private final UserMapper userMapper;

    private final FileServiceImpl fileService;

    public UserApi(UserMapper userMapper, FileServiceImpl fileService) {
        this.userMapper = userMapper;
        this.fileService = fileService;
    }


    @ApiOperation("用户管理列表")
    @PostMapping("/list")
    @RoleValid
    public ResultVo list(@RequestBody UserListRequest request) {
        var user = StaticVariable.getUser();
        QueryWrapper<Object> lambdaQueryWrapper = new QueryWrapper<>();
        if (user.getIsAdmin().equals("1")) {
            lambdaQueryWrapper.ne("u.is_admin", "2");
        }
        if (StrUtil.isNotEmpty(request.getNickName())) {
            lambdaQueryWrapper.like("u.nick_name", request.getNickName());
        }
        if (StrUtil.isNotEmpty(request.getUserName())) {
            lambdaQueryWrapper.like("u.user_name", request.getUserName());
        }
        if (request.getState() != StateEnum.ALL) {
            lambdaQueryWrapper.eq("u.state", request.getState());
        } else {
            lambdaQueryWrapper.ne("u.state", StateEnum.DEL);
        }
        if (StrUtil.isNotEmpty(request.getRole())) {
            lambdaQueryWrapper.eq("u.role", request.getRole());
        }
        IPage<User> userIPage = userMapper.selectUserPage(request.getPage(), lambdaQueryWrapper);
        return ResultUtil.page(userIPage);
    }

    /**
     * 创建或更新用户
     *
     * @return
     */
    @PostMapping("/addOrUpdate")
    @RoleValid
    @ApiOperation("增加或修改用户")
    public ResultVo userAddOrUpdate(@RequestBody User user) {
        user.setPassword(null);
        if (StrUtil.isBlank(user.getId())) {
            Integer count = user.selectCount(new LambdaQueryWrapper<User>().eq(User::getUserName, user.getUserName()));
            if (count > 0)
                return ResultUtil.failedMessage("该账号已存在");
            user.resetPwd();
        }
        user.insertOrUpdate();
        return ResultUtil.success();
    }

    /**
     * 重置密码
     *
     * @return
     */
    @PostMapping("/resetPwd")
    @RoleValid
    @ApiOperation("重置用户密码")
    public ResultVo resetPwd(@RequestBody User user) {
        if (StrUtil.isNotEmpty(user.getId())) {
            user.resetPwd();
            user.updateById();
            return ResultUtil.success();
        }
        return ResultUtil.failed();
    }

    /**
     * 更新用户头像
     *
     * @return
     */
    @PostMapping("/updateHead")
    @RoleValid
    @ApiOperation("更新用户头像")
    public ResultVo updateHead(@RequestParam("file") MultipartFile multipartFile) {
        User user = StaticVariable.getUser();
        String headImgKey = fileService.uploadFile(multipartFile, "userHead");
        user.setHeadImg(headImgKey);
        user.updateById();
        return ResultUtil.success(headImgKey);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @PostMapping("/updatePassword")
    @RoleValid
    @ApiOperation("用户修改密码")
    public ResultVo updatePassword(@RequestBody @Valid UpdatePasswordRequest request) {
        User user = StaticVariable.getUser().selectById();
        if (user.getPassword().equals(SecureUtil.sha1(request.getPassword()))) {
            user.setPassword(SecureUtil.sha1(request.getNewPassword()));
            user.updateById();
            return ResultUtil.success("修改成功", null);
        }
        return ResultUtil.failed("密码错误", null);
    }

}
